<?php

/**
 *  促销抽奖
 *
 * @author Administrator
 */

namespace Home\Controller;

use Think\Controller;
use Home\Model\Game;
use Home\Model\Tool;
use Think\JSON;
use Think\ITime;
use Think\IFilter;
use Think\IReq;
use Think\Log;

use Org\Net\Packet;

class GameController extends Controller {
    public function index(){
        $game_id = IFilter::act(IReq::get("id"));
        $code_id = IFilter::act(IReq::get("codeid"));
        
        $game = M('game')->where(array('id' => $game_id))->find();
        //dump($game);die;
        
        $prize_log = M('do_prize')->where(array('game_id' => $game_id, 'codeid' => $code_id))->count('id');
        if($game && $game['is_close'] == 0){
            $game['total'] = $game['num'] - $prize_log;
        }
        //dump($prize_log);die;
        
        $this->assign('game', $game);
        
        $this->assign("game_id", $game_id);
        $this->assign("code_id", $code_id);
        $this->display('jiugongge');
    }

    public function jiugongge() {
        //prize表示奖项内容，v表示中奖几率(若数组中七个奖项的v的总和为100，如果v的值为1，则代表中奖几率为1%，依此类推)

        $game_id = IFilter::act(IReq::get("game_id"));
        $code_id = IFilter::act(IReq::get("code_id"));
        $where = array("game_id"=>$game_id);
        $prize_arr = M('prize')->where($where)->select();
        
        $game_set = M('game')->where("id=$game_id")->find();
       
        $sum = 0;
        foreach ($prize_arr as $k=>$v) {
            $sum += intval($v['chance']);
            $arr[$v['id']] = $v['chance'];
        }
        if($sum<100){
            $arr['-1'] = 100 - $sum;
        }
        
        
        $prize_id =Game:: get_rand($arr); //根据概率获取奖项id
        
        foreach($prize_arr as $k=>$v){ //获取前端奖项位置
            if($v['id'] == $prize_id){
                $index = $k;
                 //中奖了要看当前中奖的个数是否超过设置的最大中奖个数
                 $zjNum = M('do_prize')->where("prize_id=$prize_id")->count();
                 if($zjNum>=$v['num']){
                     $prize_id = -1;
                 }
                 break;
            }
        }
        if($prize_id == -1){
            //未中奖
            $res['prize_grade'] = $game_set['failtext'];
            $res['prize_name'] = $game_set['failtext'];
        }else{
            $res = $prize_arr[$index]; //中奖项
            if($res['type']==1){
                //查找优惠券
                $res['coupon_id'] = $res['prize_name'];
                $coupon = M('coupon')->where('id='.$res['prize_name'])->find();
                $res['prize_name'] = $coupon['title'];
            }elseif($res['type']==2){
                $res['prize_name'] = $res['prize_name']."元微信红包";
            }
        }
        
        $do_prize_data = array(
            'codeid' => $code_id,
            'prize_id' => ($prize_id == -1) ? 0 : $prize_id,
            'status' => 0,
            'game_id' => $game_id,
            'time' => ITime::getNow('Y-m-d H:i:s') 
        );
        $do_prize_id = M('do_prize')->add($do_prize_data);
        
        //生成优惠券
        if ($res['type'] == 1) {
            //优惠券，生成优惠券
            $coupon['coupon_code'] = "JGG" . date("mdHi", time()) . rand(1000, 9999);
            $coupon['coupon_id'] = $res['coupon_id'];
            $coupon['prize_id'] = $data['prize_id'];
            $coupon['do_prize_id'] = $do_prize_id;
            M('coupon_list')->add($coupon);
        }
        $prize_site = mt_rand(0,7);

        if($res['num'] != 0 || $res['num']==null){
            $data['prize_grade'] = $res['prize_grade'];
            $data['prize_name'] = $res['prize_name'];
            $data['prize_site'] = $prize_site;//前端奖项从-1开始
            $data['prize_id'] = $prize_id;
            $data['type'] = $res['type'];
            $data['coupon_id'] = $res['coupon_id'];
            $data['do_prize_id'] = $do_prize_id;
            echo json_encode($data);            
        }
    }

    public function add(){
        $do_prize_id = IFilter::act(IReq::get("do_prize_id"));
        $data['prize_id'] = IFilter::act(IReq::get("id"));
        /*
        if($data['prize_id'] != 0){
            $data['status'] = 1;
            $m = M('prize');
            $id= $data['prize_id'];
            $num = $m->where("id=$id")->getField('num');
            $res['id'] = $id;
            $res['num'] = $num-1;
            $m->save($res);
        }
        */
        $data['id'] = $do_prize_id;
        $data['mobile'] = IFilter::act(IReq::get("phone"));
        $data['name'] = IFilter::act(IReq::get("name"));
        $data['addr'] = IFilter::act(IReq::get("addr"));
        $data['game_id'] = IFilter::act(IReq::get("game_id"));
        $data['codeid'] = IFilter::act(IReq::get("code_id"));
        //$data['time'] = ITime::getNow('Y-m-d H:i:s');
        M('do_prize')->save($data);
        
        //判断中奖类型
        $prize_type = IFilter::act(IReq::get("prize_type"));
        if(!empty($prize_type) && $prize_type == 1){
            //查找优惠券
            $coupon = M('coupon_list')->where(array('do_prize_id' => $do_prize_id))->find();
            echo json_encode($coupon);
        }
    }
    
    /*
     * 获取微信红包
     */
    public function wx_hongbao() {
        $do_prize_id = IFilter::act(IReq::get("do_prize_id"));
        $do_prize = M('do_prize')->find($do_prize_id); 
        if(!$do_prize){
            $message = "中奖信息不存在";
            $this->redirect('Game/mes', array('id' => $do_prize_id, 'mes' => $message));
        }
        if($do_prize['status'] == '1'){
            $message = '奖品已经领取，禁止重复领奖';
            $this->redirect('Game/mes', array('id' => $do_prize_id, 'mes' => $message));
        }
        
        $gameObj = M('game as g');
        $field = 'g.*, s.name as name, p.prize_name as amount, p.num as nums';
        $join = array(
            'sm_seller as s on g.seller_id = s.id',
            'sm_prize as p on g.id = p.game_id'
        );
        $where = array(
            'g.id' => $do_prize['game_id'],
            'p.id' => $do_prize['prize_id'],
        );
        
        $game = $gameObj->where($where)->field($field)->join($join)->find();
        
        
        //获取红包金额
        if(is_array($amount = explode(':', $game['amount']))){
            if($amount[0] == $amount[1]){
                $game['amount'] = $amount[0] * 100;
            }  else {
                $game['amount'] = mt_rand($amount[0] * 100, $amount[1] * 100);
                //Game::getBonus($game['total'], $game['nums'], $amount[1], $amount[0]);
                //Game::getBonus('100', $game['nums'], $amount[1], $amount[0]);
            }
        }  else {
            $game['amount'] = $game['amount'] * 100;
        }
        
        $config =M('seller_wx')->where(array('seller_id' => $game['seller_id']))->find();

        $code = $_GET['code'];
        $packet = new Packet($config);
        if (!empty($code)) {
            $param['param'] = 'access_token';
            $param['code'] = $code;

            //获取用户openid信息
            $userinfo = $packet->route('userinfo', $param);
            $userinfo['nickname'] = Game::filterEmoji($userinfo['nickname']);
            $data = array(
                'id' => $do_prize_id,
                'prize' => number_format($game['amount']/100,2),
                'name' => $userinfo['nickname'],
                'remark' => JSON::encode($userinfo)
            );
            M('do_prize')->save($data);       
            if (empty($userinfo['openid'])) {
                $message = '用户未授权，不能领取';
                $this->redirect('Game/mes', array('id' => $do_prize_id, 'mes' => $message));
            }

            //调取支付方法
            $res = $packet->route('wxpacket', array('openid' => $userinfo['openid']), $game);
            if($res == 'SUCCESS'){
                M('do_prize')->save(array('id' => $do_prize_id, 'status' => '1', 'time' => ITime::getNow('Y-m-d H:i:s')));
                $message = '红包已发放，请到微信中领取';
                $this->redirect('Game/mes', array('id' => $do_prize_id, 'mes' => $message));
            }  else {
                $this->redirect('Game/mes', array('id' => $do_prize_id, 'mes' => $message));
            }
        } else {
            $packet->route('userinfo');
        }
    }
    
    public function mes(){
        $do_prize_id = IFilter::act(IReq::get("id"));
        $mes = IFilter::act(IReq::get("mes"));
        $prizeObj = M('do_prize as d');
        $join = 'left join sm_prize as p on p.id = d.prize_id';
        $where = array(
            'd.id' => $do_prize_id
        );
        $field = 'd.*, p.prize_name as prize_name';
        $prize = $prizeObj->where($where)->join($join)->field($field)->find();
        //$price = explode(':',$prize['prize_name']);
        
        /*
        switch ($price[0]) {
            case 1:
                $prize['img'] = 'one';
                break;
            case 2:
                $prize['img'] = 'two';
                break;
            case 10:
                $prize['img'] = 'ten';
                break;
            case 50:
                $prize['img'] = 'fifty';
                break;
            case 100:
                $prize['img'] = 'hundred';
                break;
            default:
                $prize['img'] = '11';
                break;
        }
         * */
        if($prize['prize_id'] == 0){
            $prize['img'] = '22';
            $game = M('game')->where(array('id' => $prize['game_id']))->find();
            //dump($prize);die;
            $mes = $game['failtext'];
        }else{
            $prize['img'] = '11';
        }
        if(!$mes){
            if($prize['status'] == 0){
                $mes = '奖金未发送，点此重新发放';
            }else{
                $mes = '奖金已发放，请到微信中领取';
            }
        }
        //dump($prize);die;
        $this->assign('prize', $prize);
        $this->assign('mes', $mes);
        $this->display('mes');
    }
    
    //微信红包
    public function hongbao(){
        $code_id = IFilter::act(IReq::get("codeid"));
        $game_id = IFilter::act(IReq::get("id"));
        
        //判断是否抽过奖
        $prize = M('do_prize')->where(array('codeid' => $code_id))->find();
        if($prize){
            $this->redirect('Game/mes', array('id' => $prize['id']));
        }
        
        $where = array("game_id"=>$game_id);
        $prize_arr = M('prize')->where($where)->selects('id');
        //dump($prize_arr);
        //已中奖数量
        $do_prize_num = M('do_prize')->where(array('game_id' => $game_id))->field('prize_id,count(prize_id) as num')->group('prize_id')->selects('prize_id');

        $game_set = M('game')->where("id=$game_id")->find();
       
        $sum = 0;
        $arr = array();
        foreach ($prize_arr as $k => $v) {
            $sum += ($v['chance']);
            $arr[$k] = $v['chance'];
            if($v['num'] <= $do_prize_num[$k]['num']){
                unset($arr[$k]);
            }
        }

        if($sum<1000){
            //未中奖概率
            $arr['-1'] = 1000 - $sum;
        }
        //dump($prize_arr);die;
       
        
        $prize_id =Game:: get_rand($arr); //根据概率获取奖项id
        //dump($prize_id);die;
        
        if($do_prize_num >= $prize_arr[$prize_id]){
            unset($arr[$prize_id]);
            $prize_id = Game:: get_rand($arr);
        }

        if($prize_id == -1){
            //未中奖
            $res['prize_grade'] = $game_set['failtext'];
            $res['prize_name'] = $game_set['failtext'];
        }else{
            $res = $prize_arr[$index]; //中奖项
            if($res['type']==1){
                //查找优惠券
                $res['coupon_id'] = $res['prize_name'];
                $coupon = M('coupon')->where('id='.$res['prize_name'])->find();
                $res['prize_name'] = $coupon['title'];
            }elseif($res['type']==2){
                $res['prize_name'] = $res['prize_name']."元微信红包";
            }
        }
        
        $do_prize_data = array(
            'codeid' => $code_id,
            'prize_id' => ($prize_id == -1) ? 0 : $prize_id,
            'status' => 0,
            'game_id' => $game_id,
            'time' => ITime::getNow('Y-m-d H:i:s') 
        );
        
        $do_prize_id = M('do_prize')->add($do_prize_data);
        if($do_prize_data['prize_id'] == 0){
            $this->redirect('Game/mes', array('id' => $do_prize_id));
        }else{
            $this->redirect('wx_hongbao', array('do_prize_id' => $do_prize_id));
        }
        
    }

}
